package zzzhc.image.recognize.filter;

import zzzhc.image.recognize.Filter;
import zzzhc.image.recognize.RecognizeContext;

public class RemoveNoiseFilter implements Filter {

	private static final long serialVersionUID = 1092850292292145624L;

	public void doFilter(RecognizeContext context) {
		int h = context.getHeight();
		int w = context.getWidth();
		for (int y = 0; y < h; y++) {
			for (int x = 0; x < w; x++) {
				int p00 = context.getValue(x - 1, y - 1);
				int p01 = context.getValue(x, y - 1);
				int p02 = context.getValue(x + 1, y - 1);
				int p10 = context.getValue(x - 1, y);
				int p11 = context.getValue(x, y);
				int p12 = context.getValue(x + 1, y);
				int p20 = context.getValue(x - 1, y + 1);
				int p21 = context.getValue(x, y + 1);
				int p22 = context.getValue(x + 1, y + 1);
				int count = p00 + p01 + p02 + p10 + p11 + p12 + p20 + p21 + p22;

				if (p11 == 1) {
					if (count == 4) {
						// 1 1 1
						// 0 1 0
						if ((p00 + p01 + p02 == 3) || (p00 + p10 + p20 == 3)
								|| (p20 + p21 + p22 == 3)
								|| (p02 + p12 + p22 == 3)) {
							context.setValue(x, y, 0);
						}
					} else if (count == 2) {
						// 1 0
						// 0 1
						if (p00 + p20 + p02 + p22 == 1) {
							context.setValue(x, y, 0);
						}
					} else if (count==1) {
						context.setValue(x, y, 0);
					}
				}
			}
		}
	}
}
